using System;
using System.Collections.Generic;

namespace ChessKit.Common
{
  internal class KeyedObjectsPool<TKey, TValue>
    where TValue : class
  {
    private readonly Func<TKey, TValue> _factory;
    private readonly DicCache<TKey, Queue<TValue>> _dic;

    public KeyedObjectsPool(Func<TKey, TValue> factory = null)
    {
      _factory = factory;
      _dic = new DicCache<TKey, Queue<TValue>>(k => new Queue<TValue>());
    }

    public TValue Aquire(TKey key)
    {
      var items = _dic.Get(key);
      if (items.Count == 0)
        if (_factory == null)
          throw new InvalidOperationException("Pool is empty");
        else return _factory(key);
      return items.Dequeue();
    }
    public void Release(TKey key, TValue item)
    {
      _dic.Get(key).Enqueue(item);
    }
  }
}